import React, { useState } from "react";
import { Button } from "react-vant";
import axios from "axios"
const App = () => {

   const [text,setText]=useState([])
  const handleText = () => {
    const input = document.createElement("input");
    input.type = "file";
    input.click();

    input.onchange = () => {
      const file = input.files[0];
      if(!file){
        return ''
      }
      const fileReader = new FileReader();
      fileReader.readAsDataURL(file);
      fileReader.onload = async() => {
        const base64 = fileReader.result;

        const AK = "C1RRshT40VTIRhnE6H5Zcv91";
        const SK = "qkqO3orNdx8APiVcZZzhfFwY99xTqOPA";

        function getAccessToken() {
          let options = {
            method: "POST",
            url:
              "/baidu/oauth/2.0/token?grant_type=client_credentials&client_id=" +
              AK +
              "&client_secret=" +
              SK,
          };
          return new Promise((resolve, reject) => {
            axios(options)
              .then((res) => {
                resolve(res.data.access_token);
              })
              .catch((error) => {
                reject(error);
              });
          });
        }

        async function getData() {
          var options = {
            method: "POST",
            url:
              "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=" +
              (await getAccessToken()),
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
              Accept: "application/json",
            },
            data: {
              detect_direction: "false",
              image: base64,
              paragraph: "false",
              probability: "false",
              multidirectional_recognize: "true",
            },
          };

          return axios(options)
           
        }

       const result=await getData() 

       console .log(result)

        setText(result.data.words_result)
      };
    };
  };
  return (
    <div>
      <Button block round type="primary" onClick={handleText}>
        进行文字识别
      </Button>

      <div>
        <h2>识别后的内容:</h2>
         
          {
             text.map((item,i)=>{
               return <p key={i}>{item.words}</p>
             })
          }
      </div>
    </div>
  );
};

export default App;
